// 用户认证服务

// 从localStorage获取用户列表
const getUsers = () => {
  const users = localStorage.getItem('users')
  return users ? JSON.parse(users) : []
}

// 保存用户列表到localStorage
const saveUsers = (users) => {
  localStorage.setItem('users', JSON.stringify(users))
}

// 检查用户是否已登录
export const isLoggedIn = () => {
  return localStorage.getItem('user') !== null
}

// 获取当前登录用户
export const getCurrentUser = () => {
  const user = localStorage.getItem('user')
  return user ? JSON.parse(user) : null
}

// 登录用户
export const loginUser = (username, password) => {
  // 在实际应用中，这里应该发送请求到后端进行验证
  // 这里为了演示，我们从localStorage中验证用户
  const users = getUsers()
  const user = users.find(u => u.username === username && u.password === password)
  
  if (user) {
    // 登录成功，保存用户信息（不包含密码）
    const userInfo = {
      id: user.id,
      username: user.username,
      email: user.email,
      avatar: user.avatar || null
    }
    localStorage.setItem('user', JSON.stringify(userInfo))
    return { success: true, user: userInfo }
  }
  
  return { success: false, message: '用户名或密码错误' }
}

// 注册用户
export const registerUser = (username, password, confirmPassword, email) => {
  // 表单验证
  if (!username || !password || !confirmPassword || !email) {
    return { success: false, message: '请填写所有必填字段' }
  }
  
  if (password !== confirmPassword) {
    return { success: false, message: '两次输入的密码不一致' }
  }
  
  // 检查用户名是否已存在
  const users = getUsers()
  if (users.some(u => u.username === username)) {
    return { success: false, message: '用户名已存在' }
  }
  
  // 检查邮箱是否已存在
  if (users.some(u => u.email === email)) {
    return { success: false, message: '邮箱已被注册' }
  }
  
  // 创建新用户
  const newUser = {
    id: Date.now().toString(), // 简单的ID生成方式
    username,
    password, // 注意：在实际应用中，密码应该加密存储
    email,
    avatar: null
  }
  
  // 保存用户
  users.push(newUser)
  saveUsers(users)
  
  return { success: true, message: '注册成功' }
}

// 退出登录
export const logoutUser = () => {
  localStorage.removeItem('user')
}

// 切换账号（实际上就是退出登录）
export const switchAccount = () => {
  logoutUser()
}

// 保存用户头像
export const saveUserAvatar = (avatarUrl) => {
  const user = getCurrentUser()
  if (user) {
    user.avatar = avatarUrl
    localStorage.setItem('user', JSON.stringify(user))
    
    // 同时更新用户列表中的头像
    const users = getUsers()
    const index = users.findIndex(u => u.id === user.id)
    if (index !== -1) {
      users[index].avatar = avatarUrl
      saveUsers(users)
    }
    
    return user
  }
  return null
}

// 获取用户信息（包含更多详细信息）
export const getUserInfo = () => {
  const user = getCurrentUser()
  if (user) {
    // 从用户列表中获取更完整的用户信息
    const users = getUsers()
    const fullUser = users.find(u => u.id === user.id)
    if (fullUser) {
      return {
        ...user,
        registrationDate: fullUser.registrationDate || Date.now() - 30 * 24 * 60 * 60 * 1000, // 默认30天前注册
        lastLogin: fullUser.lastLogin || Date.now(),
        status: 'active'
      }
    }
  }
  return null
}

// 获取用户书架
export const getBookshelf = () => {
  const user = getCurrentUser()
  if (user) {
    const key = `bookshelf_${user.id}`
    const bookshelf = localStorage.getItem(key)
    return bookshelf ? JSON.parse(bookshelf) : null
  }
  return null
}

// 获取浏览记录
export const getBrowseHistory = () => {
  const user = getCurrentUser()
  if (user) {
    const key = `browse_history_${user.id}`
    const history = localStorage.getItem(key)
    return history ? JSON.parse(history) : null
  }
  return null
}

// 获取关注收藏
export const getFavorites = () => {
  const user = getCurrentUser()
  if (user) {
    const key = `favorites_${user.id}`
    const favorites = localStorage.getItem(key)
    return favorites ? JSON.parse(favorites) : null
  }
  return null
}

// 获取荣誉称号
export const getHonors = () => {
  const user = getCurrentUser()
  if (user) {
    const key = `honors_${user.id}`
    const honors = localStorage.getItem(key)
    return honors ? JSON.parse(honors) : null
  }
  return null
}

// 获取账户余额
export const getAccountBalance = () => {
  const user = getCurrentUser()
  if (user) {
    const key = `balance_${user.id}`
    const balance = localStorage.getItem(key)
    return balance ? JSON.parse(balance) : { coins: 0, cash: 0 }
  }
  return { coins: 0, cash: 0 }
}

// 保存账户余额
export const saveAccountBalance = (balance) => {
  const user = getCurrentUser()
  if (user) {
    const key = `balance_${user.id}`
    localStorage.setItem(key, JSON.stringify(balance))
    return true
  }
  return false
}

// 获取月票数量
export const getMonthlyTickets = () => {
  const user = getCurrentUser()
  if (user) {
    const key = `monthly_tickets_${user.id}`
    const tickets = localStorage.getItem(key)
    return tickets ? parseInt(tickets) : 0
  }
  return 0
}

// 设置月票数量
export const setMonthlyTickets = (count) => {
  const user = getCurrentUser()
  if (user) {
    const key = `monthly_tickets_${user.id}`
    localStorage.setItem(key, count.toString())
    return true
  }
  return false
}

// 获取推荐票数量
export const getRecommendedTickets = () => {
  const user = getCurrentUser()
  if (user) {
    const key = `recommended_tickets_${user.id}`
    const tickets = localStorage.getItem(key)
    return tickets ? parseInt(tickets) : 0
  }
  return 0
}

// 设置推荐票数量
export const setRecommendedTickets = (count) => {
  const user = getCurrentUser()
  if (user) {
    const key = `recommended_tickets_${user.id}`
    localStorage.setItem(key, count.toString())
    return true
  }
  return false
}

// 获取优惠卡券
export const getCoupons = () => {
  const user = getCurrentUser()
  if (user) {
    const key = `coupons_${user.id}`
    const coupons = localStorage.getItem(key)
    return coupons ? JSON.parse(coupons) : []
  }
  return []
}

// 获取充值记录
export const getRechargeRecords = () => {
  const user = getCurrentUser()
  if (user) {
    const key = `recharge_records_${user.id}`
    const records = localStorage.getItem(key)
    return records ? JSON.parse(records) : []
  }
  return []
}

// 获取消费记录
export const getConsumptionRecords = () => {
  const user = getCurrentUser()
  if (user) {
    const key = `consumption_records_${user.id}`
    const records = localStorage.getItem(key)
    return records ? JSON.parse(records) : []
  }
  return []
}

// 获取我的收益
export const getMyEarnings = () => {
  const user = getCurrentUser()
  if (user) {
    const key = `earnings_${user.id}`
    const earnings = localStorage.getItem(key)
    return earnings ? JSON.parse(earnings) : { total: 0, pending: 0 }
  }
  return { total: 0, pending: 0 }
}